window.PointOperator = function(option){
	option = option||{};
	this.map = option.map;
	this.div = option.div;
	this.typesDiv = option.typesDiv;
	this.searchResult = option.searchResult;
	this.buttonClass = "pointOperator_button";
	this.searchResultMarkers = {};
	this.typesInfo = [];
	this.init();
}

window.PointOperator.prototype = {
	init:function(){
		this.initQuery();
		this.initAddPoint();
	},
	initQuery:function(){
		var filter = {type:'gettypes',value:null};
		this.query(filter);
	},
	initAddPoint:function(){
		var me = this;
		var root = $("#"+this.div);
		var addPointButton = $("<div></div>").appendTo(root);
		addPointButton.addClass(this.buttonClass);
		addPointButton.addClass(this.buttonClass+"_add");
		var addPointListener;
		addPointButton.click(function(){
				if(addPointListener){
					google.maps.event.removeListener(addPointListener);
					addPointListener = undefined;
				}
				addPointListener = google.maps.event.addListener(me.map, 'click', function(event) {
			    google.maps.event.removeListener(addPointListener);
			    me.addPointMarker(event.latLng);
			});
		});
		addPointButton.mousedown(function(){
			addPointButton.addClass("heighlight");
		});
		addPointButton.mouseup(function(){
			addPointButton.removeClass("heighlight");
		});
		
	},
	
	addPointMarker:function(latLng){
		var marker = new google.maps.Marker({
	        position: latLng, 
	        map: this.map
    	});
    	var infowindow = this.createAddPointInfoWindow(marker);
	  	google.maps.event.addListener(marker, 'click', function() {
		  infowindow.open(map,marker);
		});
	},
	
	createAddPointInfoWindow:function(marker){
		var values = {};
		if(marker.extData){
			values = marker.extData;
		}
		else{
			marker.extData = values;
		}
		var me = this;
		var rootDiv = $("#addpointInfoWindowContent_template").clone().attr("id","addpointInfoWindowContent").css("display","block");
		
		//填充主类别、子类别下拉列表
    	var mainTypeSelect = rootDiv.find("div[fieldName='maintype'] select");
    	mainTypeSelect.empty();
    	for (var i = 0; i < this.typesInfo.length; i++) {
    		var maintype = this.typesInfo[i];
    		var mainTypeOption = $("<option></option>").val(maintype.id).text(maintype.name).appendTo(mainTypeSelect);
    		if(i==0){
    			var subtypes = maintype.subTypes;
    			var subtypeSelect = rootDiv.find("div[fieldName='subtype'] select");
    			for (var j = 0; j < subtypes.length; j++) {
					var subtype = subtypes[j];
					var subtypeOption = $("<option></option>").val(subtype.id).text(subtype.name).appendTo(subtypeSelect);
				}
    			$("<option></option>").val("newField").text("新建...").appendTo(subtypeSelect);
    			subtypeSelect.change(function(){
    				var selectOption = $(this).find("option:selected");
    				var selctedID = selectOption.val();
    				if(selctedID=='newField'){
    					$(this).next("input").removeAttr("disabled");
    				}else{
    					$(this).next("input").attr("disabled","true");
    				}
    			});
    		}
    	}
    	//添加新建项到主类别下拉列表
    	$("<option></option>").val("newField").text("新建...").appendTo(mainTypeSelect);
    	//主类别事件
    	mainTypeSelect.change(function(){
    		var selectOption = $(this).find("option:selected");
			var selctedID = selectOption.val();
			if(selctedID=='newField'){
				$(this).next("input").removeAttr("disabled");
				rootDiv.find("div[fieldName='subtype']").find("input").removeAttr("disabled");
			}else{
				$(this).next("input").attr("disabled","true");
				rootDiv.find("div[fieldName='subtype']").find("input").attr("disabled","true");
			}
			var subtypes = [];
			for (var m = 0; m < me.typesInfo.length; m++) {
				if(me.typesInfo[m].id==selctedID){
					subtypes = me.typesInfo[m].subTypes;
				}
			}
			var subtypeSelect = rootDiv.find("div[fieldName='subtype'] select");
			subtypeSelect.empty();
			for (var j = 0; j < subtypes.length; j++) {
				var subtype = subtypes[j];
				var subtypeOption = $("<option></option>").val(subtype.id).text(subtype.name).prependTo(subtypeSelect);
			}
			$("<option></option>").val("newField").text("新建...").appendTo(subtypeSelect);
			subtypeSelect.change(function(){
				var selectOption = $(this).find("option:selected");
				var selctedID = selectOption.val();
				if(selctedID=='newField'){
					$(this).next("input").removeAttr("disabled");
				}else{
					$(this).next("input").attr("disabled","true");
				}
			});
		});
		
		//提交按钮事件
		var submit = $(rootDiv).find(".submitButton input");
    	submit.click(function(){
    		//点位置信息
    		values['geometry'] = {lat:marker.position.lat(),lng:marker.position.lng()};
    		//name文本框的值
			values['name'] = rootDiv.find("div[fieldName='name'] input").val();
			//描述文本框的值
			values['vicinity'] = rootDiv.find("div[fieldName='vicinity'] textarea").val();
			//类别的值
			values['maintype'] = rootDiv.find("div[fieldName='maintype'] input").val();
			if(values['maintype']==""){
				values['maintype'] = rootDiv.find("div[fieldName='maintype'] select option:selected").text();
			}
			//子类的值
			values['subtype'] = rootDiv.find("div[fieldName='subtype'] input").val();
			if(values['subtype']==""){
				values['subtype'] = rootDiv.find("div[fieldName='subtype'] select option:selected").text();
			}
    		
		  	var url = "operator";
		  	url = encodeURI(url);
		  	//alert(JSON.stringify(values));
		  	var feature = encodeURI(JSON.stringify(values));
			$.post(
			 	url,
			 	{
			 		 method : "insert",
			 		 feature : feature
			 	},
			 	function(response){
			 		if(response!=""){
			 			var filter = {type:"id",value:response};
				 		var queryInfo = JSON.stringify(filter);
				 		var url="operator?method=query&queryInfo="+queryInfo;
		  				me.queryAndDrawMarkers(url,false,false);
				 		infowindow.setMap(null);
				 		marker.setMap(null);
				 		me.initQuery();
			 		}
			 		else{
			 			alert("添加失败！！");
			 		}
			 	},
			 	"text"
			 );
    	});
    	var infowindow = new google.maps.InfoWindow(
	    { 
	    	content: rootDiv[0]
	    });
	    infowindow.open(this.map,marker);
	    return infowindow;
	},
	
	query:function(filter){
		var me = this;
		var url = "operator";
	  	var queryInfo = JSON.stringify(filter);
	  	if(filter.type=="gettypes"){
	  		$.post(url,{
	  			method:"query",
	  			queryInfo:queryInfo
	  		},
		  		function(data){
	  				me.initTypesDiv(data);
		  		}
	  		);
	  	}else{
	  		url=url+"?method=query&queryInfo="+queryInfo;
	  		this.queryAndDrawMarkers(url,true,true);
	  	}
	},
	
	queryAndDrawMarkers:function(url,isClear,zoom){
		var me =this;
		
  		var myParser = new geoXML3.parser( {
			map : this.map,
			zoom : zoom,
			singleInfoWindow : true,
			createMarker : function(placemark,doc) {
				var marker = myParser.createMarker(placemark,doc.placemarks);
				me.addSearchResult(myParser,placemark,marker);
			},
			afterParse: function(doc){
				 me.searchResultMarkers = doc[0].placemarks;
			},
			beforeParse:function(){
				if(isClear){
					 clear();
				 }
			}
		});
	    myParser.parse(encodeURI(encodeURI(url)));
	    
	    
	    function clear(){
	    	var div = $("#"+me.searchResult);
		    div.empty();
			for (var name in me.searchResultMarkers.markers) {
	  			me.searchResultMarkers.markers[name].setMap(null);
	  		}
	    }
	},
	
	addSearchResult:function(myParser,placemark,marker){
		var me = this;
		var div = $("#"+this.searchResult);
		var a = $("<div class='result'></div>").appendTo(div);
		var title = $("<div class='resulttitle'></div>").appendTo(a);
		var address = $("<div class='resuldress'></div>").appendTo(a);
		var type = $("<div class='resultype'>类别:</div>").appendTo(a);
		title.text(placemark.name);
		address.text(placemark.description);
		var extendedDate = placemark.extendedDate;
		for(var name in extendedDate){
			type.text(type.text()+";"+extendedDate[name]);
		}
		a.click(function(){
			var gMap = me.map;
			gMap.panTo(new google.maps.LatLng(placemark.point.lat,placemark.point.lng));
			var lastMarker = myParser.lastMarker;
			if (!!lastMarker && !!lastMarker.infoWindow) {
		          lastMarker.infoWindow.close();
		        }
			myParser.lastMarker = marker;
			marker.infoWindow.open(marker.map, marker);
		})
	},
	
	
	initTypesDiv:function(data){
		var me = this;
		var kml = $(data);
		var root = $("#"+this.typesDiv);
		var tbody = root.find("tbody");
		tbody.empty(); 
		me.typesInfo=[];
		kml.find("Document").children("Folder").each(
			function(){
				var mainTypeText = $(this).children("name").text();
				var id =  $(this).attr("id");
				var mainTypeClassName = "maintype";
				var tbody = root.find("tbody");
				var tr = $("<tr></tr>").appendTo(tbody);
				var td = $("<td></td>").appendTo(tr);
				var mainTypeDiv = addAType(td,id,mainTypeText,mainTypeClassName);
				var subTypes = [];
				$(this).find("Folder").each(
					function(){
						var subTypeText =  $(this).children("name").text();
						var id =  $(this).attr("id");
						var subTypeClassName = "subtype";
						var subTypeDiv = addAType(td,id,subTypeText,subTypeClassName);
						subTypes.push({name:subTypeText,id:id});
					}
				);
				me.typesInfo.push({name:mainTypeText,subTypes:subTypes,id:id});
			}
		);
		
		function addAType(parent,id,text,className){
			var mainTypeDiv = $("<div>");
			mainTypeDiv.addClass(className);
			mainTypeDiv.appendTo(parent);
			mainTypeDiv.attr("id",id);
			var s = $("<a>").click(function(){
				var id = $(this).parent().attr("id");
				me.query({type:"id",value:id});
				return false;
			});
			s.attr("href","#")
			s.appendTo(mainTypeDiv);
			s.text(text);
			return mainTypeDiv;
		}
		
		function onResizeLeft(){
			var searchreturndiv = $("#"+me.searchResult);
	    	var p = searchreturndiv.parent();
	    	var pheight = p.height();
	    	var oheight = 0;
	    	p.children().not("#"+me.searchResult).each(function(){
	    		oheight+=$(this).height();
	    	});
	    	searchreturndiv.height(pheight-oheight-20);
	    }
		onResizeLeft();
	}
	
}
